package com.lu.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lu.model.entity.SysRole;
import com.lu.model.request.RoleQueryRequest;
import com.lu.model.request.RoleResourcesUpdateRequest;
import com.lu.model.response.Result;
import com.lu.service.SysRoleService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 角色信息表 前端控制器
 * </p>
 *
 * @author zhanglu
 * @since 2022-07-26
 */
@RequiredArgsConstructor
@RestController
@RequestMapping("/sys-role")
public class SysRoleController {

  private final SysRoleService roleService;

  @PreAuthorize("hasAuthority('/sys-role/add')")
  @PostMapping(value = "/add")
  public Result<Long> addRole(@RequestBody SysRole role){
    return Result.success(roleService.addRole(role));
  }

  @PreAuthorize("hasAuthority('/sys-role/update')")
  @PostMapping(value = "/update")
  public Result<SysRole> updateRole(@RequestBody SysRole role){
    return Result.success(roleService.updateRole(role));
  }

  @PreAuthorize("hasAuthority('/sys-role/update-status')")
  @PostMapping(value = "/update-status/{id}/{status}")
  public Result<Integer> updateStatus(@PathVariable Long id, @PathVariable Integer status){
    return Result.success(roleService.updateStatus(id, status));
  }

  @PreAuthorize("hasAuthority('/sys-role/delete')")
  @PostMapping(value = "/delete/{id}")
  public Result<String> deleteRole(@PathVariable Long id){
    return Result.success(roleService.deleteRole(id));
  }

  @PreAuthorize("hasAuthority('/sys-role/page-list')")
  @PostMapping(value = "/page-list")
  public Result<Page<SysRole>> pageList(@RequestBody RoleQueryRequest request){
    return Result.success(roleService.pageList(request));
  }

  @PostMapping(value = "/list")
  public Result<List<SysRole>> roleList(@RequestBody RoleQueryRequest request){
    return Result.success(roleService.roleList(request));
  }

  @PreAuthorize("hasAuthority('/sys-role/sort')")
  @PostMapping("/sort")
  public Result<List<SysRole>> sort(@RequestBody List<Long> ids){
    return Result.success(roleService.sort(ids));
  }

  /**
   * 更新角色资源关系
   * @param request
   * @return 用户id
   */
  @PreAuthorize("hasAuthority('/sys-role/update-resources')")
  @PostMapping(value = "/update-resources")
  public Result<String> updateResources(@RequestBody @Validated RoleResourcesUpdateRequest request){
    return Result.success(roleService.updateResources(request));
  }

  /**
   * 角色详情
   * @param id
   * @return
   */
  @PreAuthorize("hasAuthority('/sys-role/get')")
  @GetMapping(value = "/get/{id}")
  public Result<SysRole> getById(@PathVariable Long id){
    return Result.success(roleService.getByRoleId(id));
  }

}
